<template>
	<div class="base-info-content">
		<el-form ref="ruleFormRef" :model="goodsInfoData" :rules="rules" label-width="150px">
			<el-form-item label="商品规格：" class="pt10" v-if="false">
				<section style="display: flex; flex-direction: column;">
					<section>
						<el-col v-for="(item, index) of goodsInfoData.specList" :key="index" :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
							<section class="specItemBox">
								<el-input v-model="item.name" class="width180" placeholder="请输入规格名称"  />
								<el-icon size="20" color="#999" class="close-tag" @click="delSpec(index)">
									<CircleCloseFilled />
								</el-icon>
							</section>
							<div class="ml20 mt15 flex">
								<span style="border-left: 1px solid #cdd0d6;border-bottom: 1px solid #cdd0d6;width: 20px;height: 20px;margin-right: 20px"></span>
								<section class="flex" style="flex-wrap: wrap;">
									<section class="mr20 mb20 specItemBox" style="position: relative;width: min-content;" v-for="(item1, index1) of item.childItem" :key="index1">
										<el-input v-model="item1.name" class="width180" placeholder="请输入规格值" />
										<el-icon size="20" color="#999" class="close-tag" @click="delSpecItem(index,index1)">
											<CircleCloseFilled />
										</el-icon>
									</section>
									<el-button type="primary" @click="addSpecItemChildFun(index)">添加规格值</el-button>
								</section>
							</div>
						</el-col>
						<el-col :span="24" class="mb20">
							<el-button type="primary"  @click="addSpecFun">添加规格项</el-button>
							<el-button type="primary"  @click="tplDialogFun()">快捷模板</el-button>
						</el-col>
					</section>
				</section>
			</el-form-item>
			<el-form-item label="活动售价：" v-if="goodsInfoData.skuList.length > 0" 
				:rules="[{ required: true, message: '活动售价不能为空', trigger:'blur'}, { pattern: /^[1-9]\d*(\.\d+)?$/, message: '请输入正确的金额', trigger: 'blur' }]">
				<el-input class="width420" v-model="goodsInfoData.priceValue" placeholder="请输入活动售价">
					<template #prepend>
						<el-select v-model="goodsInfoData.priceType" placeholder="请选择" class="width150">
							<el-option label="一口价" :value=1 />
							<el-option label="累加价" :value=2 />
						</el-select>
					</template>
					<template #append>
						<span>元</span>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item label="活动属性：" v-if="goodsInfoData.skuList.length > 0">
				<el-table :data="goodsInfoData.skuList" border>
					<el-table-column v-for="(item, index) of goodsInfoData.specList" :prop="item.key"
						:label="item.name" :key="index" width="100">
						<template #default="scope">
							<span>{{ scope.row.skuSpecList[index].name }}</span>
						</template>
					</el-table-column>
					<el-table-column label="图片" align="center">
						<template #default="scope">
							<section style="display: inline-block;" @click="addImg('skuImgUrl', 0, scope.$index)">
								<el-image v-if="scope.row.skuImgUrl != '' && scope.row.skuImgUrl != null"
									style="width:32px; height: 32px;border-radius: 5px;" :src="scope.row.skuImgUrl" fit="cover" />
								<section v-else class="selector-img" style="width:32px; height: 32px;border-radius: 5px;">
									<el-icon size="32" color="#999" style="width:32px; height: 32px;border-radius: 5px;" >
										<Plus />
									</el-icon>
								</section>
							</section>
						</template>
					</el-table-column>
					<el-table-column label="划线价" show-overflow-tooltip v-if="goodsInfoData.salesChannel.includes(2)">
						<template v-slot:header>
							划线价
							<el-popover placement="top-start" trigger="hover"
								content="线上展示使用，建议填写商品指导价">
								<template #reference>
									<el-icon><QuestionFilled /></el-icon>
								</template>
							</el-popover>
						</template>
						<template v-slot="scope">
							<el-form-item :prop="`skuList.${scope.$index}.referencePrice`" 
								:rules="[{ required: true, message: '请输入', trigger:'blur'}, { pattern: /^[1-9]\d*(\.\d+)?$/, message: '请输入正确的金额', trigger: 'blur' }]">
								<el-input v-model="scope.row.referencePrice" placeholder="请输入" >
									<template #append>
										<span>元</span>
									</template>
								</el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column label="最低价" show-overflow-tooltip v-if="goodsInfoData.salesChannel.includes(1)">
						<template v-slot:header>
							最低价
							<el-popover placement="top-start" trigger="hover"
								content="商品控价价格，低于该价格商品禁止销售">
								<template #reference>
									<el-icon><QuestionFilled /></el-icon>
								</template>
							</el-popover>
						</template>
						<template v-slot="scope">
							<el-form-item :prop="`skuList.${scope.$index}.lowPrice`" 
								:rules="[{ required: true, message: '请输入', trigger:'blur'}, { pattern: /^[1-9]\d*(\.\d+)?$/, message: '请输入正确的金额', trigger: 'blur' }]">
								<el-input v-model="scope.row.lowPrice" placeholder="请输入" >
									<template #append>
										<span>元</span>
									</template>
								</el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column label="成本价" show-overflow-tooltip>
						<template v-slot:header>
							成本价
							<el-popover placement="top-start" trigger="hover"
								content="商品成本价格，用来核算商品利润，不填写则无法核算利润">
								<template #reference>
									<el-icon><QuestionFilled /></el-icon>
								</template>
							</el-popover>
						</template>
						<template v-slot="scope">
							<el-form-item :prop="`skuList.${scope.$index}.costPrice`" 
								:rules="[{ required: true, message: '请输入', trigger:'blur'}, { pattern: /^[1-9]\d*(\.\d+)?$/, message: '请输入正确的金额', trigger: 'blur' }]">
								<el-input v-model="scope.row.costPrice" placeholder="请输入" >
									<template #append>
										<span>元</span>
									</template>
								</el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column label="虚拟库存" show-overflow-tooltip v-if="goodsInfoData.salesChannel.includes(2)">
						<template v-slot:header>
							预警库存
							<el-popover placement="top-start" trigger="hover"
								content="商品库存警戒值，等于低于该值时，需要及时补货，避免缺货">
								<template #reference>
									<el-icon><QuestionFilled /></el-icon>
								</template>
							</el-popover>
						</template>
						<template v-slot="scope">
							<el-form-item :prop="`skus.${scope.$index}.stock`" 
								:rules="[{ required: true, message: '不能为空', trigger:'blur'},{ pattern: /^[1-9]\d*$/, message: '请输入正整数', trigger: 'blur' }]">
								<el-input v-model="scope.row.stock" placeholder="请输入" />
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column label="线下销量" show-overflow-tooltip v-if="goodsInfoData.salesChannel.includes(2)">
						<template v-slot:header>
							线下销量
							<el-popover placement="top-start" trigger="hover"
								content="线上销量展示使用，可以填写商品在线下渠道或其他渠道的总销量">
								<template #reference>
									<el-icon><QuestionFilled /></el-icon>
								</template>
							</el-popover>
						</template>
						<template v-slot="scope">
							<el-form-item :prop="`skus.${scope.$index}.offlineSales`" 
								:rules="[{ required: true, message: '不能为空', trigger:'blur'},{ pattern: /^[1-9]\d*$/, message: '请输入正整数', trigger: 'blur' }]">
								<el-input v-model="scope.row.offlineSales" placeholder="请输入" />
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column label="关联商品">
						<template #default="scope">
							<el-button link type="primary"  @click="relevanceGoods(scope.$index)">关联商品</el-button>
						</template>
					</el-table-column>
					<el-table-column prop="address" label="操作">
						<template #default>
							<el-button   text type="primary" >
								移除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-form-item>
			<section style="text-align: center; margin: 50px 0;">
				<el-button type="primary" @click="previousStep">上一步</el-button>
				<el-button type="primary" @click="nextStep(ruleFormRef)">下一步</el-button>
			</section>
		</el-form>
		<AddInformation ref="addInformationRef" @selectFun="selectFun" />
		<relevanceGoodDialog @selectItemFun="selectItemFun" ref="relevanceGoodDialogRef" />
		<tplDialog @selectSpecFun="selectSpecFun" ref="tplDialogRef" />
	</div>
</template>

<script setup lang="ts" name="funWangEditor">
import { reactive, ref, onMounted, defineAsyncComponent } from 'vue';
import { Plus,CircleCloseFilled,QuestionFilled } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import '/@/theme/tableTool.scss';
import { templateList, } from "/@/api/commodity";
import { ElMessage } from 'element-plus';
import { goodsInfo } from '/@/stores/goods';
const goodsInfoData = goodsInfo()
const AddInformation = defineAsyncComponent(() => import('/@/components/information/AddInformation.vue'))
const relevanceGoodDialog = defineAsyncComponent(() => import('/@/views/commodity/goodList/components/relevanceGoodDialog.vue'))
const tplDialog = defineAsyncComponent(() => import('/@/views/commodity/goodList/components/tplDialog.vue'))
const addInformationRef = ref()
const relevanceGoodDialogRef = ref()
const tplDialogRef = ref()
const emit = defineEmits(['stepChange'])
const ruleFormRef = ref<FormInstance>()
const state = reactive({
	addFileType: '',
	operateIndex:0,
	// 可用模板列表
	specTemplateList: [] as Array<any>,
	addSpecItemChild:[] as Array<any>,
		batchSettingsTable: [{
		skuImgUrl:'',
		retailPrice: null,
		referencePrice:null,
		lowPrice:null,
		costPrice:null,
		unit: '',
		stock: null,
		warnStock: null,
		offlineSales:null,
		merchantCode:null,
		barCode:null,
		relatedSku: [] as Array<any>,
	}] as Array<any>,
})

const rules = reactive<FormRules<any>>({
})

// 获取可用模板
const getTemplateList = async () => {
	let param = {
		pageNum:1,
		pageSize:100,
		typeId: 2,
	}
	const { results } = await templateList(param);
	state.specTemplateList = results.records
}

// 图片选中
const addImg = (type: string, isArr: Number, index?: number) => {
	state.addFileType = type;
	if(index != undefined){
		state.operateIndex = index;
	}
	addInformationRef.value.openDialog(isArr)
}

// 图片选中回调
const selectFun = (fileList: any) => {
	if (state.addFileType == 'skuImgUrl') {
		goodsInfoData.skuList[state.operateIndex].skuImgUrl = fileList[0]
	}
}

const relevanceGoods = (index:number)  => {
	state.operateIndex = index;
	if(index == 99999){
		relevanceGoodDialogRef.value.openDialog('relatedSku',state.batchSettingsTable[0].relatedSku,goodsInfoData.spuType);
	}else{
		relevanceGoodDialogRef.value.openDialog('relatedSku',goodsInfoData.skuList[index].giveGoods.ruleList,goodsInfoData.spuType);
	}
}

// sku管理商品回调
const selectItemFun = (type:String,list:any)  => {
	if(state.operateIndex == 99999){ //批量商品 
		state.batchSettingsTable[0].relatedSku = list;
	}else if(type == 'relatedSku'){
		const listA = list.map((item:any) =>{
			return {
				data:item.data,
				itemId: item.data.skuId,
				itemName: item.data.spuName,
				itemNum: null
			}
		})
		goodsInfoData.skuList[state.operateIndex].giveGoods = {
			// selectId:null,
			ruleList:listA
		};
	}
}

// 打开选择模板
const tplDialogFun = () => {
	tplDialogRef.value.openDialog(1)
}

// 选中模板后获取模板内规格项
const selectSpecFun = (tmpData:any) => {
	goodsInfoData.specList = tmpData;
	console.log(goodsInfoData.specList)
	creatSkuList();
};

// 添加规格项
const addSpecFun = () => {
	const item = { name:'#', childItem: [ { id:null, name:'#'}]};
	goodsInfoData.specList.push(item);
	creatSkuList();
}

// 移除某一种规格组
const delSpec = (x:number) => {
	goodsInfoData.specList.splice(x,1)
	creatSkuList();
}

// 移除规格中某一项规格
const delSpecItem = (x:number,y:number)=>{
	goodsInfoData.specList[x].childItem.splice(y,1)
	creatSkuList();
}

// 给规格项中某一项添加规格
const addSpecItemChildFun = (x:number)=>{
	goodsInfoData.specList[x].childItem.push({name:'#'})
	creatSkuList();
}

// 创建商品规格列表
const creatSkuList = async () => {
	const attr = goodsInfoData.specList;
	const skus = calculateCartesianProduct(attr).map((product: any[]) => {  
		const sku = JSON.parse(JSON.stringify(goodsInfoData.multipleData));
		sku.skuSpecList = [];
		product.forEach((value: any) => {  
			sku.skuSpecList.push(value)
		});
		return sku;
	});
	goodsInfoData.skuList = skus;
}

// 多规格生成
const calculateCartesianProduct = (attr:any) =>{
	if (attr.length === 0) {
		return [[]]; // 返回一个空数组，表示没有属性可选
	} else {
		const firstAttribute = attr[0];
		const remainingAttributes = attr.slice(1);
		const firstAttributeValues = firstAttribute.childItem;
		const remainingProduct = calculateCartesianProduct(remainingAttributes);
		return firstAttributeValues.flatMap((value: any) => remainingProduct.map((product: any) => [value].concat(product)));
	}
}


// 批量添加数据
const batchAdd = () =>{
	if(goodsInfoData.skuList.length > 0){
		goodsInfoData.skuList.map((obj:any) =>{
			// let batchData = state.batchSettingsTable[0]
			// obj.skuImgUrl = batchData.skuImgUrl;
			// obj.retailPrice = batchData.retailPrice;
			// obj.referencePrice = batchData.referencePrice;
			// obj.lowPrice = batchData.lowPrice;
			// obj.costPrice = batchData.costPrice;
			// obj.unit = batchData.unit;
			// obj.stock = batchData.stock;
			// obj.warnStock = batchData.warnStock;
			// obj.offlineSales = batchData.offlineSales;
			// obj.merchantCode = batchData.merchantCode;
			// obj.barCode = batchData.barCode;
			// obj.relatedSku = obj.relatedSku.length == 0 ? batchData.relatedSku : obj.relatedSku;
		})
	}else{
		ElMessage({
			type: 'warning',
			message: '请先添加规格项',
		})
	}
}


// 页面加载时
onMounted(() => {
	// 获取规格模板列表
	getTemplateList();
});

// 上一步
const previousStep = () => {
	emit('stepChange', 'first')
}

// 下一步
const nextStep = async (formEl: FormInstance | undefined) => {
	if(goodsInfoData.skuList.length == 0){
		return ElMessage.warning('暂无商品规格');
	}
	if (!formEl) return
	await formEl.validate((valid) => {
		if (valid) {
			emit('stepChange', 'third')
		} else {
			ElMessage.warning('请补全商品信息');
		}
	})
}
</script>

<style lang="scss" scoped>
@import '../../../../theme/other.scss';
.base-info-content {
	.form-ele-size {
		width: 260px;
	}

	.line-title {
		font-size: 18px;
		padding: 8px 12px;
		background-color: #eceef0;
		border-radius: 6px;
		margin-bottom: 15px;
	}

	.selector-img {
		width: 64px;
		height: 64px;
		border: 1px solid #ededed;
		border-radius: 5px;
		cursor: pointer;
		display: flex;
		justify-content: center;
		align-items: center;

		&:hover {
			background-color: #f5f5f5;
			border: 1px solid #e4e3e3;
		}
	}
	.specItemBox{
		position: relative;
		width: min-content
	}
	.specItemBox .close-tag{
		position: absolute;
		cursor: pointer;
		top:-6px; 
		right:-6px;
		display: none;
	}

	.specItemBox:hover .close-tag {
		display: inline; /* 鼠标悬浮时显示关闭标签 */
	}
}
</style>
